import { useTableActionRedux } from "@/components/ant-ext-table/redux/HAdminContext";
import SysRole, { SysRoleEntity, SelectedMenuArr } from "@/api/sys-role";
import SysMenu, { SysMenuTreePlus, arrIndex } from "@/api/sys-menu";
import { useActionTitle, useEdit, useHandle } from "@/common/hooks";
import HModal from "@/components/ant-ext/HModal";
import { HSearchTree } from "@/components/ant-ext/HSearchTree";
import { Key, useEffect, useState } from "react";


export default function RoleMenu() {
    const { action, reset } = useTableActionRedux<SysRoleEntity>()
    const { title } = useActionTitle(action, SysRole.ROLE_MENU_MAPPING)
    const [loading, setLoading] = useState(false)
    const [menuTree, setMenuTree] = useState<SysMenuTreePlus[]>([])
    const [checkedKeys, setCheckedKeys] = useState<Key[]>([])
    const [refreshExpandedKeys, setRefreshExpandedKeys] = useState<Key[]>([])
    const close = () => {
        reset()
    }

    const reload = useHandle(() => SysMenu.selectTree({
        setLoading,
        success: (data => {
            const arr: never[] = []
            const treeDataMapping = arrIndex(arr, data)
            setMenuTree(treeDataMapping)
            setRefreshExpandedKeys(treeDataMapping.map((p: { key: any; }) => p.key))
        })
    }), [loading,setLoading])

    useEffect(() => {
        if (action.match(SysRole.ROLE_MENU)) {

            SysRole.selectRoleMenu({
                params: { roleId: action.getRow()?.id }, success: (data) => {
                    const arr: never[] = []
                    const treeDataSelectMapping = SelectedMenuArr(arr, data)
                    reload()
                    setCheckedKeys(treeDataSelectMapping) //已选中
                }
            })
        }
    }, [action])

    const doSubmit = useEdit(SysRole.doEditRoleMenu, {
        success: () => {
            close()
        }
    })


    return <HModal onCancel={close} type={"setUp"} style={{ width: "400px", height: "200px" }}
        onOk={() => doSubmit({ body: { roleId: action.getRow()?.id, selected: checkedKeys } })}
        visible={title !== undefined}
        title={title}
    >
        <HSearchTree checkable={true}
            refreshExpandedKeys={refreshExpandedKeys}
            checkedKeys={checkedKeys}
            checkStrictly
            onCheck={(keys) => {
                // @ts-ignore
                setCheckedKeys(keys.checked)
            }}
            showIcon={true}
            showLine={true} treeData={menuTree} />
    </HModal>
}